#include "pch.h"
#include "ICenter.h"


void ICenter::outCenterHigh(vector<KLine*>* kLines, float* pfOUT) {
	vector<Center*>* centers = findAllExtendCenter(kLines);

	for (int i = 0; i < centers->size(); i++) {
		Center* c = centers->at(i);
		for (int j = c->m_startIdx; j <= c->m_endIdx; j++) {
			pfOUT[j] = c->m_high;
		}
	}

	clearCenters(centers);
}

void ICenter::outCenterLow(vector<KLine*>* kLines, float* pfOUT) {
	vector<Center*>* centers = findAllExtendCenter(kLines);

	for (int i = 0; i < centers->size(); i++) {
		Center* c = centers->at(i);
		for (int j = c->m_startIdx; j <= c->m_endIdx; j++) {
			pfOUT[j] = c->m_low;
		}
	}

	clearCenters(centers);
}

void ICenter::clearCenters(vector<Center*>* centers) {
	for (int i = 0; i < centers->size(); i++) {
		delete centers->at(i);
	}
	delete centers;
}

vector<Center*>* ICenter::findAllCenter(vector<KLine*>* kLines) {
	vector<Center*>* centers = new vector<Center*>();
	for (int i = kLines->size() - 1; i > 0; i--) {
		Center* center = findLastCenter(kLines, i);
		if (center != NULL) {
			centers->push_back(center);
			i = center->m_startIdx - 1;
		}
	}
	return centers;
}

Center* ICenter::findLastExtendCenter(vector<KLine*>* kLines, int idx) {
	Center* center = findLastCenter(kLines, idx);
	if (center == NULL) {
		return NULL;
	}
	int lastCenterIdx = center->m_startIdx - 1;
	while (lastCenterIdx > 0) {
		Center* nextCenter = findLastCenter(kLines, center->m_startIdx - 1);
		if (nextCenter == NULL) {
			return center;
		}
		if (nextCenter->m_lowest < center->m_highest && nextCenter->m_highest > center->m_lowest) {
			center->m_highest = max(center->m_highest, nextCenter->m_highest);
			center->m_high = max(center->m_high, nextCenter->m_high);
			center->m_low = min(center->m_low, nextCenter->m_low);
			center->m_lowest = min(center->m_lowest, nextCenter->m_lowest);
			center->m_startIdx = nextCenter->m_startIdx;
			
			lastCenterIdx = center->m_startIdx - 1;
		}
		else {
			return center;
		}
	}
	return center;
}

vector<Center*>* ICenter::findAllExtendCenter(vector<KLine*>* kLines) {
	vector<Center*>* centers = new vector<Center*>();
	for (int i = kLines->size() - 1; i > 0; i--) {
		Center* center = findLastExtendCenter(kLines, i);
		if (center != NULL) {
			centers->push_back(center);
			i = center->m_startIdx - 1;
		}
	}
	return centers;
}